package com.earthea.scaffold.system.controller;

import com.earthea.common.constant.NumberConstant;
import com.earthea.common.util.JacksonUtils;
import com.earthea.scaffold.common.aop.aspect.ControllerLogAspect;
import com.earthea.scaffold.common.entity.BaseCollectionRsp;
import com.earthea.scaffold.common.entity.BaseDataRsp;
import com.earthea.scaffold.common.entity.BaseRsp;
import com.earthea.scaffold.common.enums.OperateTypeEnum;
import com.earthea.scaffold.common.util.SecurityUtils;
import com.earthea.scaffold.common.util.ServletUtils;
import com.earthea.scaffold.domain.LoginUser;
import com.earthea.scaffold.domain.Menu;
import com.earthea.scaffold.domain.OperLog;
import com.earthea.scaffold.domain.User;
import com.earthea.scaffold.system.entity.request.LoginReq;
import com.earthea.scaffold.system.entity.request.RegisterReq;
import com.earthea.scaffold.system.entity.response.LoginRsp;
import com.earthea.scaffold.system.entity.vo.RouterVo;
import com.earthea.scaffold.system.service.MenuService;
import com.earthea.scaffold.system.service.OperLogService;
import com.earthea.scaffold.system.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api")
public class LoginController {
    private static final Logger LOGGER = LoggerFactory.getLogger("operLog");

    @Autowired
    private UserService userService;

    @Autowired
    private OperLogService operLogService;

    @Autowired
    private MenuService menuService;

    @PostMapping("/register")
    public BaseRsp register(@RequestBody @Validated RegisterReq req) {
        long start = System.currentTimeMillis();
        OperLog operLog = new OperLog();
        operLog.setOperateType(OperateTypeEnum.OTHER);
        operLog.setTitle("注册");
        operLog.setRequestMethod(ServletUtils.getRequest().getMethod());
        operLog.setRequestUrl(StringUtils.substring(ServletUtils.getRequest().getRequestURI(), 0, 255));
        ControllerLogAspect.getExt(operLog);
        operLog.setRequest(StringUtils.substring(JacksonUtils.toJsonAnonymize(req), 0, 2000));
        BaseDataRsp<User> register;
        try {
            LOGGER.info(operLog.requestLog(req.getUsername()));
            register = userService.register(req);
            operLog.setResponse(StringUtils.substring(JacksonUtils.toJsonAnonymize(register), 0, 2000));
            if (register.isSuccess()) {
                operLog.setStatus(NumberConstant.IntegerStatus.SUCCESS);
                operLog.setCreateBy(register.getData().getUserId());
            } else {
                operLog.setStatus(NumberConstant.IntegerStatus.FAILED);
                operLog.setCreateBy(-1L);
            }
            LOGGER.info(operLog.responseLog(req.getUsername()));
        } catch (Exception e) {
            operLog.setStatus(NumberConstant.IntegerStatus.FAILED);
            operLog.setCreateBy(-1L);
            final String str = e.getMessage();
            operLog.setErrMsg(StringUtils.substring(str, 0, 2000));
            LOGGER.error(operLog.errLog(req.getUsername()), e);
            throw e;
        } finally {
            operLog.setCostTime(System.currentTimeMillis() - start);
            // 保存数据库
            operLogService.insert(operLog);
        }
        register.setData(null);
        return register;
    }

    /**
     * 登录方法
     *
     * @param loginReq 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public BaseRsp login(@RequestBody @Validated LoginReq loginReq) {
        long start = System.currentTimeMillis();
        OperLog operLog = new OperLog();
        operLog.setOperateType(OperateTypeEnum.OTHER);
        operLog.setTitle("登录");
        operLog.setRequestMethod(ServletUtils.getRequest().getMethod());
        operLog.setRequestUrl(StringUtils.substring(ServletUtils.getRequest().getRequestURI(), 0, 255));
        ControllerLogAspect.getExt(operLog);
        operLog.setRequest(StringUtils.substring(JacksonUtils.toJsonAnonymize(loginReq), 0, 2000));
        LoginRsp login;
        try {
            LOGGER.info(operLog.requestLog(loginReq.getLoginName()));
            login = userService.login(loginReq);
            operLog.setResponse(StringUtils.substring(JacksonUtils.toJsonAnonymize(login), 0, 2000));
            if (login.isSuccess()) {
                operLog.setStatus(NumberConstant.IntegerStatus.SUCCESS);
                operLog.setCreateBy(login.getUserId());
            } else {
                operLog.setStatus(NumberConstant.IntegerStatus.FAILED);
                operLog.setCreateBy(-1L);
            }
            LOGGER.info(operLog.responseLog(loginReq.getLoginName()));
        } catch (Exception e) {
            operLog.setStatus(NumberConstant.IntegerStatus.FAILED);
            operLog.setCreateBy(-1L);
            final String str = e.getMessage();
            operLog.setErrMsg(StringUtils.substring(str, 0, 2000));
            LOGGER.error(operLog.errLog(loginReq.getLoginName()), e);
            throw e;
        } finally {
            operLog.setCostTime(System.currentTimeMillis() - start);
            // 保存数据库
            operLogService.insert(operLog);
        }
        return login;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("/getInfo")
    public BaseDataRsp<LoginUser> getInfo() {
        return new BaseDataRsp<>(SecurityUtils.getLoginUser());
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("/getRouters")
    public BaseCollectionRsp<RouterVo> getRouters() {
        List<Menu> menus = menuService.selectMenuTreeByUserId();
        return new BaseCollectionRsp<>(menuService.buildMenus(menus));
    }

}
